<?php

/**
 * There's only two steps: database configuration and basic settings
 */


$configFilePath = '../euso-core/configs/db.php';


$step = 'dbconfig';
$message = '';


$db_ready = FALSE;

$db_host = 'localhost';
$db_username = '';
$db_password = '';
$db_name = 'euso';
$db_prefix = 'euso_';


function sql_inject($filename)
{
	global $db_prefix;

	$queryString = file_get_contents($filename);
	//TODO: don't use explode!
	$array = explode(';', $queryString);
	foreach ($array as $q) {
		$q = str_replace('{DB_TABLE_PREFIX}', $db_prefix, trim($q));
		if (empty($q)) {
			continue;
		}
		if (!mysql_query($q)) {
			echo mysql_error()."\n";
		}
	}
}


if (file_exists($configFilePath)) {

	// load and check connection
	require_once $configFilePath;

	$dbConn = @mysql_connect($dbConfig['host'], $dbConfig['username'], $dbConfig['password']);

	if (!$dbConn || !@mysql_select_db($db_name)) {
		$message = "Configuration file exists but the connection to the database could not be established with the configuration. Please check that the database server is running. Or, you can delete existing configuration file to generate new one.";
		$step = 'halt';
	} else {
		//TODO: validate database contents
		$valid = FALSE;

		$tables = array();
		$tablesResult = mysql_query("SHOW TABLES");
		while ($row = mysql_fetch_row($tablesResult)) {
			if ($row[0] === $db_prefix .'options') {
				$valid = TRUE;
				break;
			}
		}

		if ($valid) {
			//TODO: check if the table has contents
			$message = "Installation done.";
			$step = 'done';
		} else {

			sql_inject('./mysql/euso.sql');
			sql_inject('./mysql/log.sql');
			sql_inject('./mysql/account.sql');

			$step = 'initbasic';
		}
	}

} else {
//TODO: check whether the this script has writing access to the configuration file
// If it hasn't, warn
}

if (isset($_POST['submit'])) {

	if (isset($_POST['db_host'])) {
		$db_host = $_POST['db_host'];
	}
	if (isset($_POST['db_username'])) {
		$db_username = $_POST['db_username'];
	}
	if (isset($_POST['db_password'])) {
		$db_password = $_POST['db_password'];
	}
	if (isset($_POST['db_name'])) {
		$db_name = $_POST['db_name'];
	}
	if (isset($_POST['db_prefix'])) {
		$db_prefix = $_POST['db_prefix'];
	}

	$dbConn = @mysql_connect($db_host, $db_username, $db_password);

	if ($dbConn) {
		if (@mysql_select_db($db_name)) {
			// Write the configuration file
			$cfgFile = fopen($configFilePath, 'w');
			//TODO: failure handling

			fwrite($cfgFile, "<?php\n\n");
			fwrite($cfgFile, "\$dbConfig = array();\n\n");
			fwrite($cfgFile, "\$dbConfig['host'] = '". $db_host ."';\n");
			fwrite($cfgFile, "\$dbConfig['username'] = '". $db_username ."';\n");
			fwrite($cfgFile, "\$dbConfig['password'] = '". $db_password ."';\n");
			fwrite($cfgFile, "\$dbConfig['dbname'] = '". $db_name ."';\n");
			fwrite($cfgFile, "\$dbConfig['prefix'] = '". $db_prefix ."';\n");

			fclose($cfgFile);

			header("Refresh: 0; url=");

		} else {
			//TODO: tell the admin to check the write permission or show a textarea contains the configuration
			$message = "Could not open file for writing.";

			$step = 'dbconfig';
		}
	} else {
		$message = "Could not establish connection to the database. Please re-check the information.";
		$step = 'dbconfig';
	}
}



?>
<?php if ($step ==='dbconfig'): ?>
<HTML>
	<HEAD>
		<title>Euso Installation &ndash; Database Configuration</title>
	</HEAD>
	<BODY>
		<div><?php echo $message; ?></div>
		<h1>Euso Installation &ndash; Database Configuration</h1>
		<form action="" method="POST">
			<dl>
				<dt><label for="db_username">Database username:</label></dt>
				<dd><input type="text" name="db_username" size="36" maxLength="500" value="<?php echo $db_username; ?>" /></dd>
				<dt><label for="db_password">Database password:</label></dt>
				<dd><input type="text" name="db_password" size="36" maxLength="500" value="<?php echo $db_password; ?>" /></dd>
				<dt><label for="db_name">Database name:</label></dt>
				<dd><input type="text" name="db_name" size="36" maxLength="500" value="<?php echo $db_name; ?>" /></dd>
				<dt><label for="db_prefix">Database table prefix:</label></dt>
				<dd><input type="text" name="db_prefix" size="36" maxLength="500" value="<?php echo $db_prefix; ?>" /></dd>
				<dt><label for="db_host">Database host:</label></dt>
				<dd><input type="text" name="db_host" size="36" maxLength="500" value="<?php echo $db_host; ?>" /></dd>
				<dt><label for="submit">&nbsp;</label></dt>
				<dd>
					<input type="submit" name="submit" value="Next" />
					<input type="hidden" name="step" value="<?php echo $step; ?>" />
				</dd>
			</dl>
		</form>
	</BODY>
</HTML>
<?php elseif ($step === 'initbasic'): ?>
<HTML>
	<HEAD>
		<title>Euso Installation &ndash; Basic Settings</title>
	</HEAD>
	<BODY>
		<div><?php echo $message; ?></div>
		<h1>Euso Installation &ndash; Basic Settings</h1>
		<form action="" method="POST">
			<dl>
				<dt><label for="site_name">Site Name:</label></dt>
				<dd><input type="text" name="site_name" size="36" maxLength="500" value="<?php echo $site_name; ?>" /></dd>
				<dt><label for="site_tagline">Tagline:</label></dt>
				<dd><input type="text" name="site_tagline" size="36" maxLength="500" value="<?php echo $site_tagline; ?>" /></dd>
				<dt><label for="site_adminname">Administrator Name:</label></dt>
				<dd><input type="text" name="site_adminname" size="36" maxLength="500" value="<?php echo $site_adminname; ?>" /></dd>
				<dt><label for="site_adminpass">Administrator Password:</label></dt>
				<dd><input type="text" name="site_adminpass" size="36" maxLength="500" value="<?php echo $site_adminpass; ?>" /></dd>
				<dt><label for="site_adminemail">Administrative Email:</label></dt>
				<dd><input type="text" name="site_adminemail" size="36" maxLength="500" value="<?php echo $site_adminemail; ?>" /></dd>
				<dt><label for="submit">&nbsp;</label></dt>
				<dd>
					<input type="submit" name="submit" value="Next" />
					<input type="hidden" name="step" value="<?php echo $step; ?>" />
				</dd>
			</dl>
		</form>
	</BODY>
</HTML>
<?php else: ?>
<HTML>
	<HEAD>
		<title>Euso Installation</title>
	</HEAD>
	<BODY>
		<div><?php echo $step; ?>: <?php echo $message; ?></div>
	</BODY>
</HTML>
<?php endif; ?>
